iT邦幫忙

2023 iThome 鐵人賽

DAY 22
0

一、json與xml程式範例(1)
昨天介紹json與xml的
今天來介紹常見的程式範例:
先宣告一個類別

class animal
{
	public int id { get; set; }
	public string name { get; set; }
	public string color { get; set; }
}

再來是宣告物件

animal cat = new animal();
cat.id = 1;
cat.name = "小白";
cat.color = "白";

以下就是把物件轉字串的函式,這個要在nuget安裝Newtonsoft這個元件

string result = JsonConvert.SerializeObject(cat, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine("result: " + result);

以下是產生的結果
https://ithelp.ithome.com.tw/upload/images/20231007/20163340q1DXu0G7Zj.png

以下是用字串轉XML的語法

XDocument xmlDocument = JsonConvert.DeserializeXNode(result.ToString(), "root");
Console.WriteLine("xmlDocument: " + xmlDocument);

以下是產生的結果https://ithelp.ithome.com.tw/upload/images/20231007/20163340ynWfuFYFdm.png

二、json與xml程式範例(2)
這也可以用chatGPT找範例
以下是用字串轉XML的語法
這個例子主要是提到可以用Object.Parse(json);把字串換轉為json格式,其餘程式與上一例相同就不再重複貼圖

    static void Main()
    {
        string json = @"{
            'person': {
                'name': 'John',
                'age': 30,
                'city': 'New York',
                'phones': {
                    'home': '212-555-1234',
                    'office': '646-555-4567'
                },
                'skills': ['Python', 'JavaScript']
            }
        }";

        JObject jsonObject = JObject.Parse(json);
        XDocument xmlDocument = JsonConvert.DeserializeXNode(jsonObject.ToString(), "root");

        Console.WriteLine(xmlDocument.ToString());
    }

以上是用字串轉json與字串轉XML的語法


上一篇
json與XML比較、線上資源、格式轉換
下一篇
各種存取資料庫的元件介紹(ODBC、OLEDB、SQLClient)、讀取元件介紹(SqlDataReader、SqlDataAdapter)
系列文
研究visual studio+MSSQL各項技術30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言